<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input
                        v-model="queryParams.roleName"
                        placeholder="请输入角色名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="角色标识" prop="roleKey">
                <el-input
                        v-model="queryParams.roleKey"
                        placeholder="请输入角色标识"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="状态 " prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态 " clearable>
                    <el-option
                            v-for="dict in sys_normal_disable"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['system:role:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['system:role:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['system:role:remove']"
                >删除
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="编码" align="center" prop="id"/>
            <el-table-column label="角色名称" align="center" min-width="120" prop="roleName"/>
            <el-table-column label="角色标识" align="center" prop="roleKey"/>
            <el-table-column label="显示顺序" align="center" prop="orderNum"/>
            <el-table-column label="状态 " align="center" prop="status">
                <template #default="scope">
                    <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
            <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
            <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button
                            v-if="!scope.row.admin"
                            type="primary"
                            text
                            icon="Edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['system:role:edit']"
                    >修改
                    </el-button>
                    <el-button
                            v-if="!scope.row.admin"
                            type="danger"
                            text
                            icon="Delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['system:role:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改角色信息对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form v-if="open" ref="roleRef" :model="form" :rules="rules" label-width="125px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称"/>
                </el-form-item>
                <el-form-item label="角色标识" prop="roleKey">
                    <template #label>
                        <span>
                            <el-tooltip effect="dark" content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                                <el-icon><QuestionFilled /></el-icon>
                            </el-tooltip>
                            角色标识
                        </span>
                    </template>
                    <el-input v-model="form.roleKey" placeholder="请输入角色标识"/>
                </el-form-item>
                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number v-model="form.orderNum" controls-position="right" placeholder="请输入显示顺序"/>
                </el-form-item>
                <el-form-item label="是否外部可访问" prop="isOutside">
                    <template #label>
                        <span>
                            <el-tooltip effect="dark" content="外部角色表示公共角色，外部无需权限就可访问，如注册时角色选择列表" placement="top">
                                <el-icon><QuestionFilled /></el-icon>
                            </el-tooltip>
                            是否外部角色
                        </span>
                    </template>
                    <el-radio-group v-model="form.isOutside">
                        <el-radio
                            v-for="dict in sys_yes_no"
                            :key="dict.value"
                            :value="dict.value"
                        >{{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio
                                v-for="dict in sys_normal_disable"
                                :key="dict.value"
                                :value="dict.value"
                        >{{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单权限" prop="menuIds">
                    <el-card style="width: 100%;">
                        <el-tree
                            ref="menuTree"
                            :data="menuOptions"
                            show-checkbox
                            node-key="id"
                            :default-checked-keys="form.menuIds"
                            :props="{label: 'menuName', children: 'children'}"
                        />
                    </el-card>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Role">
import {listRole, getRole, delRole, addRole, updateRole} from "@/api/system/role";
import {listTreeMenu } from "@/api/system/menu";
import {getCurrentInstance, reactive, ref, toRefs} from "vue";

const {proxy} = getCurrentInstance();
const {sys_yes_no, sys_normal_disable} = proxy.initDict('sys_yes_no', 'sys_normal_disable');

const roleList = ref([]);
const menuTree = ref();
const menuOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null, roleKey: null, status: null
    },
    rules: {
        roleName: [
            {required: true, message: "请输入角色名称", trigger: "blur"}
        ],
        roleKey: [
            {required: true, message: "请输入角色标识", trigger: "blur"}
        ],
        orderNum: [
            {required: true, message: "请输入显示顺序", trigger: "blur"}
        ],
        isOutside: [
            {required: true, message: "请选择是否外部可访问", trigger: "change"}
        ],
        status: [
            {required: true, message: "请选择状态", trigger: "change"}
        ]
    }
});

const {queryParams, form, rules} = toRefs(data);

getList();

/** 查询角色信息列表 */
function getList() {
    loading.value = true;
    listRole(queryParams.value).then(response => {
        roleList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

/** 查询菜单树列表 */
function getMenuTreeList() {
    listTreeMenu().then(response => {
        menuOptions.value = response.data;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        createBy: null,
        createTime: null,
        deleteFlag: null,
        remark: null,
        updateBy: null,
        updateTime: null,
        roleName: null,
        roleKey: null,
        orderNum: 0,
        isOutside: "N",
        status: "0"
    };
    proxy.resetForm("roleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    getMenuTreeList();
    open.value = true;
    title.value = "添加角色信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    getMenuTreeList();
    const _id = row.id || ids.value
    getRole(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改角色信息";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["roleRef"].validate(valid => {
        if (valid) {
            form.value.menuIds = menuTree.value.getCheckedKeys();
            if (form.value.id != null) {
                updateRole(form.value).then(response => {
                    proxy.$message.success("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addRole(form.value).then(response => {
                    proxy.$message.success("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$messageBox.confirm('是否确认删除角色信息编号为"' + _ids + '"的数据项？').then(function () {
        return delRole(_ids);
    }).then(() => {
        getList();
        proxy.$message.success("删除成功");
    }).catch(() => {
    });
}

</script>
